package com.woniu.sharepark.util.websocket;



import com.woniu.sharepark.listener.SingleStateListener;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author xin
 * @date 2019/6/14 16:28
 * version v1.0
 */
@ServerEndpoint("/ws/onlineServer/{account}")
@Component
public class OnlineWebSocketServer {

    private static ConcurrentHashMap<String, OnlineWebSocketServer> servers=new ConcurrentHashMap<String, OnlineWebSocketServer>();

    private Session session;

    @OnOpen
    public void onOpen(Session session,@PathParam("account") String account){
        this.session=session;

        if (servers==null){
            servers.put(account,this);
            Integer count=servers.size();
            String countStr=count.toString();
            sendMessage(countStr);
        }else {
            if (servers.get(account)==null){
                servers.put(account,this);
                Integer count=servers.size();
                String countStr=count.toString();
                sendMessage(countStr);
            }
        }


    }


    @OnClose
    public void onClose(@PathParam("account") String account){
        servers.remove(account);
        Integer count=servers.size();
        String countStr=count.toString();
        sendMessage(countStr);

    }

    @OnMessage
    public void onMessage(String message, Session session) {

    }


    @OnError
    public void onError(Session session, Throwable error){
        error.printStackTrace();
    }

    public static void sendMessage(String message)  {


        for (String server:servers.keySet()
        ) {

            try {
                servers.get(server).session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}




